package com.zhixiang.core.command;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;

public class SortCommandImpl
  implements CriteriaCommand
{
  private String sortName;
  private String ascDesc;
  private QueryFilter filter;

  public Criteria execute(Criteria c)
  {
	  Criteria criteria=c;
    String[] as = this.sortName.split("[.]");
    if ((as != null) && (as.length > 1)) {
      for (int i = 0; i < as.length - 1; i++) {
        if (this.filter.getAliasSet().get(as[i])==null) {
        	criteria=criteria.createAlias(as[i], as[i]);
          this.filter.getAliasSet().put(as[i],criteria);
        }else{
        	criteria=(Criteria) this.filter.getAliasSet().get(as[i]);
        }
      }
    }
    if ("desc".equalsIgnoreCase(this.ascDesc))
      criteria.addOrder(Order.desc(this.sortName));
    else if ("asc".equalsIgnoreCase(this.ascDesc))
      criteria.addOrder(Order.asc(this.sortName));
    return c;
  }

  public SortCommandImpl(String s, String s1, QueryFilter queryfilter) {
    this.sortName = s;
    this.ascDesc = s1;
    this.filter = queryfilter;
  }

  public String getSortName() {
    return this.sortName;
  }

  public void setSortName(String s) {
    this.sortName = s;
  }

  public String getAscDesc() {
    return this.ascDesc;
  }

  public void setAscDesc(String s) {
    this.ascDesc = s;
  }

  public int hashCode() {
    return new HashCodeBuilder(-82280557, -700257973).append(this.sortName)
      .append(this.ascDesc).toHashCode();
  }

  public String getPartHql() {
    return this.sortName + " " + 
      this.ascDesc;
  }
}

